對於所有被包含在物件的成員來說,可以透過可見性修飾符賦予不同的讀取權。
private
:若子類別欲存取位於父類別,會出現無法存取之錯誤訊息。protected
:可同時兼顧到成員的安全性與便利性,internal
:只有被標示為internal
的成員能看見public
:任何成員都能看見open class Outer {
private val a = 1
protected open val b = 2
internal open val c = 3
val d = 4 // public by default
protected class Nested {
public val e: Int = 5
}
}
class Subclass : Outer() {
// a is not visible
// b, c and d are visible
// Nested and e are visible
override val b = 5 // 'b' is protected
override val c = 7 // 'c' is internal
}
class Unrelated(o: Outer) {
// o.a, o.b are not visible
// o.c and o.d are visible (same module)
// Outer.Nested is not visible, and Nested::e is not visible either
}